package by.blog.dao.dao.factory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Бондарчик Антон  15.11.2014.
 */
public class MysqlDaoFactory{

    private static volatile MysqlDaoFactory instance;
    private static Connection myConnection;

    private MysqlDaoFactory() {

        try {
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch (ClassNotFoundException e) {

        }
        if (myConnection == null) {

            try {

                FileInputStream fis;
                Properties properties = new Properties();
                String propFileName = "loginMysql.properties";

                InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

                properties.load(inputStream);

                String host = properties.getProperty("host");
                String login = properties.getProperty("login");
                String password = properties.getProperty("password");
                myConnection = DriverManager.getConnection(host, login, password);
            }
            catch (IOException io) {
                System.out.println("IO");
            }
            catch (SQLException e) {
                System.out.println("sql");
            }
        }
    }

    /**
     * connection to DataBase, Singleton
     * @return MysqlDaoFactory instance
     */
    public static MysqlDaoFactory getInstance() {

        if (instance == null) {
            synchronized (MysqlDaoFactory.class) {
                if (instance == null) {
                    instance = new MysqlDaoFactory();
                }
            }
        }
        return instance;
    }

    /**
     * call this method for creating dao query to DB
     * @param QUERY
     * @return PreparedStatement based on QUERY
     */
    public static PreparedStatement prepareStatement(String QUERY) {
        try {
            return myConnection.prepareStatement(QUERY);
        }
        catch (SQLException e) {
            return null;
        }
    }
}
